{% extends "app/base_site.html" %}

{% block title %} 人脸管理 {% endblock title %}

{% block stylesheets %}
  {{ block.super }}
<link rel="stylesheet" href="/static/lib/jquery/fancybox/3.5.7/jquery.fancybox.min.css" />
<style>
    .xc_face-container {
        /*background: #f5f7fa;*/
    }
    
    .xc_face-toolbar {
        background: white;
        border-radius: 6px;
        padding: 10px 14px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.06);
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        gap: 8px;
        flex-wrap: wrap;
    }
    
    .xc_modern-card {
        background: white;
        border-radius: 6px;
        padding: 10px 14px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.06);
        margin-bottom: 12px;
    }
    
    .xc_page-title {
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 400;
    }
    
    .xc_page-title i {
        margin-right: 6px;
        font-size: 16px;
        color: #3b82f6;
    }
    

    .xc_loading-spinner {
        display: inline-block;
        width: 12px;
        height: 12px;
        border: 2px solid #e5e7eb;
        border-top: 2px solid #3b82f6;
        border-radius: 50%;
        animation: xc_spin 1s linear infinite;
        margin-right: 5px;
    }
    
    @keyframes xc_spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
    }
    
    .xc_loading-text {
        color: #6b7280;
        font-size: 12px;
    }
    
    .xc_btn-modern {
        height: 30px;
        padding: 0 12px;
        font-size: 12px;
        font-weight: 400;
        border-radius: 3px;
        border: 1px solid #d1d5db;
        background: white;
        color: #374151;
        cursor: pointer;
        transition: all 0.2s;
        display: inline-flex;
        align-items: center;
        gap: 4px;
        white-space: nowrap;
        text-decoration: none;
        vertical-align: middle;
        line-height: 1;
        flex-shrink: 0;
        box-sizing: border-box;
    }
    
    .xc_btn-modern:hover {
        background: #f9fafb;
        border-color: #3b82f6;
        color: #3b82f6;
    }
    
    .xc_btn-primary {
        background: #169F85;
        color: white;
        border-color: #169F85;
    }
    
    .xc_btn-primary:hover {
        background: #14b89a;
        border-color: #14b89a;
        color: white;
        box-shadow: 0 2px 6px rgba(22, 159, 133, 0.25);
    }
    
    .xc_btn-secondary {
        background: white;
        color: #6b7280;
        border: 1px solid #d1d5db;
    }
    
    .xc_btn-secondary:hover {
        background: #f9fafb;
        color: #374151;
        border-color: #9ca3af;
    }

    .xc_control-select {
        height: 32px;
        padding: 0 10px;
        font-size: 12px;
        border: 1px solid #d1d5db;
        border-radius: 3px;
        background: white;
        color: #374151;
        cursor: pointer;
        transition: all 0.2s;
        min-width: 140px;
        line-height: 32px;
        vertical-align: middle;
        flex-shrink: 0;
        box-sizing: border-box;
        margin-bottom: 5px;
    }
    
    .xc_control-select:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
    
    .xc_status-indicator {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 3px 8px;

        border-radius: 3px;
        font-size: 11px;
        font-weight: 400;
        white-space: nowrap;
         height: 32px;
        margin-bottom: 5px;
    }
    
    .xc_status-success {
        background: #e0f2fe;
        color: #0369a1;
    }
    
    .xc_status-error {
        background: #f3f4f6;
        color: #6b7280;
    }
    
    .xc_status-indicator i {
        font-size: 10px;
    }
    
    .xc_face-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 320px));
        gap: 18px;
        margin-bottom: 16px;
    }
    
    .xc_face-card {
        background: white;
        border-radius: 6px;
        overflow: hidden;
        box-shadow: 0 1px 2px rgba(0,0,0,0.05);
        transition: all 0.2s;
        border: 1px solid #e5e7eb;
    }
    
    .xc_face-card:hover {
        box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        border-color: #3b82f6;
    }
    
    .xc_face-header {
        position: relative;
        padding: 12px;
        background: #fafafa;
        color: #374151;
        display: flex;
        align-items: center;
        gap: 10px;
        border-bottom: 1px solid #e5e7eb;
    }
    
    .xc_person-photo {
        width: 85px;
        height: 85px;
        border-radius: 8px;
        overflow: hidden;
        border: 2px solid #e5e7eb;
        background: #fff;
        flex-shrink: 0;
        cursor: pointer;
        transition: all 0.2s;
    }
    
    .xc_person-photo:hover {
        border-color: #3b82f6;
    }
    
    .xc_person-photo img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .xc_face-photo {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        overflow: hidden;
        border: 2px solid #e5e7eb;
        background: #fff;
        cursor: pointer;
        transition: all 0.2s;
        box-shadow: 0 2px 4px rgba(0,0,0,0.08);
    }
    
    .xc_face-photo:hover {
        border-color: #3b82f6;
    }
    
    .xc_face-photo img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .xc_person-info {
        flex: 1;
    }
    
    .xc_person-id {
        font-size: 11px;
        color: #6b7280;
        margin-bottom: 2px;
    }
    
    .xc_person-name {
        font-size: 14px;
        font-weight: 500;
        margin-bottom: 3px;
        color: #374151;
    }
    
    .xc_person-code {
        font-size: 11px;
        color: #6b7280;
        font-family: monospace;
    }
    
    .xc_face-id {
        display: none; /* 隐藏原来的右上角ID */
    }
    
    .xc_face-body {
        padding: 10px 12px;
    }
    
    .xc_info-row {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 6px 0;
        border-bottom: 1px solid #f3f4f6;
        font-size: 12px;
    }
    
    .xc_info-row:last-child {
        border-bottom: none;
    }
    
    .xc_info-label {
        color: #6b7280;
    }
    
    .xc_info-value {
        color: #374151;
        font-weight: 500;
    }
    
    .xc_face-actions {
        display: flex;
        gap: 8px;
        padding: 10px 12px;
        background: #fafafa;
        border-top: 1px solid #e5e7eb;
        justify-content: center;
    }
    
    .xc_btn-icon {
        flex: 0 0 auto;
        min-width: 70px;
        padding: 5px 12px;
        font-size: 12px;
        border-radius: 3px;
        border: 1px solid #d1d5db;
        background: white;
        color: #374151;
        cursor: pointer;
        transition: all 0.2s;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 3px;
        text-decoration: none;
    }
    
    .xc_btn-icon:hover {
        background: #f9fafb;
        border-color: #3b82f6;
        color: #3b82f6;
    }
    
    .xc_btn-edit {
        background: white;
        color: #374151;
        border-color: #d1d5db;
    }
    
    .xc_btn-edit:hover {
        border-color: #3b82f6;
        color: #3b82f6;
    }
    
    .xc_btn-sync {
        background: white;
        color: #374151;
        border-color: #d1d5db;
    }
    
    .xc_btn-sync:hover {
        border-color: #3b82f6;
        color: #3b82f6;
    }
    
    .xc_btn-delete {
        background: white;
        color: #374151;
        border-color: #d1d5db;
    }
    
    .xc_btn-delete:hover {
        border-color: #ef4444;
        color: #ef4444;
    }
    
    .xc_pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 8px;
        padding: 16px 0;
        background: white;
        border-radius: 6px;
    }
    
    .xc_page-btn {
        min-width: 36px;
        height: 36px;
        padding: 0 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #d1d5db;
        background: white;
        color: #6b7280;
        border-radius: 5px;
        cursor: pointer;
        font-size: 13px;
        transition: all 0.2s;
        text-decoration: none;
    }
    
    .xc_page-btn:hover:not(.active) {
        border-color: #3b82f6;
        color: #3b82f6;
    }
    
    .xc_page-btn.active {
        background: #3b82f6;
        color: white;
        border-color: #3b82f6;
    }
    
    .xc_page-info {
        font-size: 13px;
        color: #9ca3af;
        margin: 0 8px;
    }
    
    .xc_empty-state {
        text-align: center;
        padding: 80px 20px;
        color: #9ca3af;
    }
    
    .xc_empty-state i {
        font-size: 64px;
        color: #d1d5db;
        margin-bottom: 16px;
    }
    
    .xc_empty-state p {
        font-size: 14px;
        margin: 0;
    }
    
    /* 弹窗样式 */
    .xc_modal-overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1000;
    }
    
    .xc_modal-overlay.active {
        display: block;
        animation: xc_fadeIn 0.2s ease;
    }
    
    @keyframes xc_fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    
    .xc_modal-container {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        border-radius: 8px;
        width: 90%;
        max-width: 650px;
        max-height: 80vh;
        display: flex;
        flex-direction: column;
        box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
        animation: xc_slideIn 0.3s ease;
    }
    
    @keyframes xc_slideIn {
        from {
            transform: translate(-50%, -48%);
            opacity: 0;
        }
        to {
            transform: translate(-50%, -50%);
            opacity: 1;
        }
    }
    
    .xc_modal-header {
        position: relative;
        padding: 14px 18px;
        border-bottom: 1px solid #e5e7eb;
        background: #fafafa;
        border-radius: 8px 8px 0 0;
    }
    
    .xc_modal-title {
        font-size: 16px;
        font-weight: 500;
        color: #374151;
    }
    
    .xc_modal-close {
        position: absolute;
        top: 12px;
        right: 16px;
        width: 30px;
        height: 30px;
        border: none;
        background: white;
        color: #6b7280;
        font-size: 20px;
        line-height: 1;
        cursor: pointer;
        padding: 0;
        border-radius: 4px;
        border: 1px solid #d1d5db;
        transition: all 0.2s;
    }
    
    .xc_modal-close:hover {
        background: #f3f4f6;
        color: #374151;
        border-color: #9ca3af;
    }
    
    .xc_modal-body {
        flex: 1;
        padding: 18px 20px;
        overflow-y: auto;
    }
    
    .xc_form-group {
        margin-bottom: 14px;
    }
    
    .xc_form-label {
        display: block;
        font-size: 13px;
        color: #374151;
        margin-bottom: 6px;
        font-weight: 500;
    }
    
    .xc_form-label .required {
        color: #ef4444;
        margin-left: 2px;
    }
    
    .xc_form-input {
        width: 100%;
        padding: 8px 12px;
        font-size: 13px;
        border: 1px solid #d1d5db;
        border-radius: 4px;
        background: white;
        color: #374151;
        transition: all 0.2s;
        height: 36px;
    }
    
    .xc_form-input:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
    
    .xc_form-input:disabled {
        background: #f9fafb;
        color: #9ca3af;
        cursor: not-allowed;
    }
    
    .xc_form-textarea {
        width: 100%;
        padding: 8px 12px;
        font-size: 13px;
        border: 1px solid #d1d5db;
        border-radius: 4px;
        background: white;
        color: #374151;
        resize: vertical;
        min-height: 80px;
        transition: all 0.2s;
    }
    
    .xc_form-textarea:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
    }
    
    .xc_file-input {
        font-size: 13px;
        color: #374151;
        height: 36px;
    }
    
    .xc_file-input::file-selector-button {
        font-size: 12px;
        color: white;
        border-radius: 4px;
        border: 1px solid #3b82f6;
        padding: 6px 12px;
        background-color: #3b82f6;
        cursor: pointer;
        margin-right: 10px;
    }
    
    .xc_file-input::file-selector-button:hover {
        background-color: #2563eb;
        border-color: #2563eb;
    }
    
    .xc_file-input {
        font-size: 13px;
        color: #374151;
        height: 36px;
    }
    
    .xc_file-input::file-selector-button {
        padding: 5px 12px;
        margin-right: 10px;
        font-size: 12px;
        color: #374151;
        background: #f3f4f6;
        border: 1px solid #d1d5db;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.2s;
        line-height: 1.2;
    }
    
    .xc_file-input::file-selector-button:hover {
        background: #e8f4f1;
        border-color: #10b981;
    }
    
    .xc_preview-images {
        display: flex;
        gap: 10px;
        margin-top: 8px;
    }
    
    .xc_preview-item {
        text-align: center;
    }
    
    .xc_preview-label {
        font-size: 11px;
        color: #6b7280;
        margin-bottom: 4px;
    }
    
    .xc_preview-img {
        width: 85px;
        height: 85px;
        object-fit: cover;
        border-radius: 4px;
        border: 1px solid #e5e7eb;
        cursor: pointer;
    }
    
    .xc_preview-img:hover {
        border-color: #3b82f6;
    }
    
    .xc_modal-footer {
        padding: 14px 18px;
        border-top: 1px solid #e5e7eb;
        text-align: right;
        background: #fafafa;
        border-radius: 0 0 8px 8px;
    }
    
    .xc_modal-btn {
        padding: 7px 18px;
        font-size: 13px;
        border-radius: 4px;
        border: 1px solid #d1d5db;
        cursor: pointer;
        margin-left: 10px;
        transition: all 0.2s;
        font-weight: 400;
        background: white;
        color: #374151;
    }
    
    .xc_modal-btn:hover {
        background: #f9fafb;
        border-color: #9ca3af;
    }
    
    .xc_modal-btn-primary {
        background: #3b82f6;
        color: white;
        border-color: #3b82f6;
    }
    
    .xc_modal-btn-primary:hover {
        background: #2563eb;
        border-color: #2563eb;
    }
    
    .right_col {
        background: #f5f7fa !important;
    }
    
    @media (max-width: 1200px) {
        .xc_face-grid {
            grid-template-columns: repeat(auto-fill, minmax(280px, 300px));
        }
        
        .xc_btn-modern {
            padding: 3px 8px;
            font-size: 11px;
        }
    }
    
    @media (max-width: 768px) {
        .xc_control-select {
            min-width: 120px;
        }
        
        .xc_face-grid {
            grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
        }
        
        .xc_face-header {
            flex-direction: row;
        }
    }
</style>
{% endblock stylesheets %}

{% block content %}
<script>
    let g_flowArray = [];
</script>

<div class="right_col" role="main">
    <div class="row">
        <div class="col-md-12">
            <div class="x_panel">
                <!-- xc page start -->
                <div class="xc_face-container">
                    <div class="xc_face-toolbar">
                        <div class="xc_page-title">
                            <i class="fa fa-user"></i>
                            人脸管理
                        </div>

                        <select id="select_flow_code" class="xc_control-select">
                            <option value="0">请选择算法</option>
                            {% for flow in flows %}
                                <script>
                                g_flowArray.push({
                                    "code":'{{ flow.code }}',
                                    "name":'{{ flow.name }}',
                                    "mode":parseInt('{{ flow.mode }}')
                                })
                                </script>
                                <option value="{{ flow.code }}">{{ flow.name }}</option>
                            {% endfor %}
                        </select>
                        
                        <button onclick="f_openAlgorithmInit()" class="xc_btn-modern xc_btn-secondary">
                            <i class="fa fa-play"></i> 开启
                        </button>
                        <button onclick="f_openAlgorithmRelease()" class="xc_btn-modern xc_btn-secondary">
                            <i class="fa fa-stop"></i> 关闭
                        </button>
                        
                        <span id="algorithm_state" class="xc_status-indicator xc_status-error">
                            <i class="fa fa-circle"></i> 未开启
                        </span>

                        <button class="xc_btn-modern xc_btn-secondary" onclick="openAddModal()">
                            <i class="fa fa-plus"></i> 添加
                        </button>
                        <button class="xc_btn-modern xc_btn-secondary" id="btn_sync">
                            <i class="fa fa-refresh"></i> 全量更新人脸库
                        </button>
                        <div>
                            <span id="top_loading" style="display: none;">
                                <span class="xc_loading-spinner"></span>
                                <span class="xc_loading-text">加载中...</span>
                            </span>
                            <span id="top_msg">{{top_msg}}</span>
                        </div>
                    </div>

                    <div class="xc_modern-card">

                        <div class="xc_face-grid">
                            {%  for d  in data %}
                            <div class="xc_face-card">
                                <div class="xc_face-header">
                                    <div class="xc_person-photo" onclick="viewImage('{{ storageDir_www }}{{ d.image_dir }}/{{ d.image_name }}')">
                                        <img src="{{ storageDir_www }}{{ d.image_dir }}/{{ d.image_name }}" alt="{{ d.name }}">
                                    </div>
                                    <div class="xc_person-info">
                                        <div class="xc_person-name">{{ d.name }}</div>
                                        <div class="xc_person-id">ID: {{ d.id }}</div>
                                        <div class="xc_person-code">编号: {{ d.custom_code }}</div>
                                    </div>
                                    <div class="xc_face-photo" onclick="viewImage('{{ storageDir_www }}{{ d.image_dir }}/{{ d.face_image_name }}')">
                                        <img src="{{ storageDir_www }}{{ d.image_dir }}/{{ d.face_image_name }}" alt="人脸">
                                    </div>
                                    <div class="xc_face-id">{{ d.id }}</div>
                                </div>
                                
                                <div class="xc_face-body">
                                    <div class="xc_info-row">
                                        <span class="xc_info-label">更新时间</span>
                                        <span class="xc_info-value">{{ d.last_update_time }}</span>
                                    </div>
                                </div>
                                
                                <div class="xc_face-actions">
                                    <button onclick="openEditModal('{{ d.code }}')" class="xc_btn-icon xc_btn-edit">
                                        <i class="fa fa-edit"></i> 编辑
                                    </button>
                                    <button onclick="f_del('{{ d.code }}')" class="xc_btn-icon xc_btn-delete">
                                        <i class="fa fa-trash"></i> 删除
                                    </button>
                                </div>
                            </div>
                            {% endfor %}
                        </div>
                        
                        {% if data|length == 0 %}
                        <div class="xc_empty-state">
                            <i class="fa fa-user-times"></i>
                            <p>暂无人脸数据</p>
                        </div>
                        {% endif %}
                    </div>

                    <div class="xc_pagination">
                        <span class="xc_page-info">共 {{ pageData.page_num }} 页 / {{ pageData.count }} 条</span>
                        {%  for d  in pageData.pageLabels%}
                          {% if d.cur == 1 %}
                            <div class="xc_page-btn active">{{ d.name }}</div>
                          {% else %}
                            <a href="/face/index?p={{d.page}}&ps={{pageData.page_size}}" class="xc_page-btn">{{ d.name }}</a>
                          {% endif %}
                        {% endfor %}
                    </div>
                </div>
                <!-- xc page end -->
            </div>
        </div>
    </div>
</div>

<!-- 人脸添加/编辑弹窗 -->
<div class="xc_modal-overlay" id="faceModal">
    <div class="xc_modal-container">
        <div class="xc_modal-header">
            <div class="xc_modal-title" id="modalTitle">添加人脸</div>
            <button class="xc_modal-close" onclick="closeFaceModal()">×</button>
        </div>
        <div class="xc_modal-body">
            <div class="xc_form-group">
                <label class="xc_form-label">编号</label>
                <input type="text" id="input_code" class="xc_form-input" disabled>
            </div>
            
            <div class="xc_form-group">
                <label class="xc_form-label">分组名称<span class="required">*</span></label>
                <input type="text" id="input_group_name" class="xc_form-input" value="default">
            </div>
            
            <div class="xc_form-group">
                <label class="xc_form-label">名称<span class="required">*</span></label>
                <input type="text" id="input_name" class="xc_form-input">
            </div>
            
            <div class="xc_form-group">
                <label class="xc_form-label">自定义编号<span class="required">*</span></label>
                <input type="text" id="input_custom_code" class="xc_form-input">
            </div>
            
            <div class="xc_form-group">
                <label class="xc_form-label">选择人员照片<span class="required">*</span></label>
                <input type="file" id="input_file" class="xc_form-input xc_file-input" accept="image/png,image/jpeg,image/jpg">
            </div>
            
            <div class="xc_form-group" id="preview_section" style="display: none;">
                <div class="xc_preview-images">
                    <div class="xc_preview-item">
                        <div class="xc_preview-label">人员照片</div>
                        <img id="preview_person" class="xc_preview-img" onclick="viewImage(this.src)">
                    </div>
                    <div class="xc_preview-item">
                        <div class="xc_preview-label">人脸特征图</div>
                        <img id="preview_face" class="xc_preview-img" onclick="viewImage(this.src)">
                    </div>
                </div>
            </div>
            
            <div class="xc_form-group">
                <label class="xc_form-label">备注</label>
                <textarea id="input_remark" class="xc_form-textarea"></textarea>
            </div>
        </div>
        <div class="xc_modal-footer">
            <button class="xc_modal-btn" onclick="closeFaceModal()">取消</button>
            <button class="xc_modal-btn xc_modal-btn-primary" onclick="submitFaceForm()">
                <span id="submit_loading" style="display: none;">
                    <span class="xc_loading-spinner"></span>
                </span>
                <span id="submit_text">提交</span>
            </button>
        </div>
    </div>
</div>
{% endblock content %}

{% block javascripts %}
  {{ block.super }}
<script src="/static/lib/jquery/fancybox/3.5.7/jquery.fancybox.min.js"></script>
<script>
    let ele_top_loading = $("#top_loading");
    let ele_top_msg = $("#top_msg");
    let eleSelectFlowCode = $("#select_flow_code");
    let eleBtnSync = $("#btn_sync");
    let eleAlgorithmState = $("#algorithm_state");

    eleSelectFlowCode.change(function () {
        let flow_code = $(this).val();
    });

    eleBtnSync.click(function () {
        f_openSyncDatabase('all')
    })

    // ============ 弹窗功能 ============
    let currentHandle = 'add'; // 'add' 或 'edit'
    let currentFaceCode = '';
    let curIsPost = false;
    
    function openAddModal() {
        currentHandle = 'add';
        currentFaceCode = generateCode();
        
        $('#modalTitle').text('添加人脸');
        $('#input_code').val(currentFaceCode);
        $('#input_group_name').val('default').prop('disabled', false);
        $('#input_name').val('');
        $('#input_custom_code').val('');
        $('#input_file').val('');
        $('#input_remark').val('');
        $('#preview_section').hide();
        
        $('#faceModal').addClass('active');
    }
    
    function openEditModal(code) {
        currentHandle = 'edit';
        currentFaceCode = code;
        
        $('#modalTitle').text('编辑人脸');
        
        // 加载人脸数据
        ele_top_loading.show();
        $.ajax({
            url: '/face/openInfo',
            type: 'get',
            data: {code: code},
            dataType: 'json',
            success: function(res) {
                ele_top_loading.hide();
                
                if(res.code === 1000 && res.info) {
                    let face = res.info;
                    
                    $('#input_code').val(face.code);
                    $('#input_group_name').val(face.group_name).prop('disabled', true);
                    $('#input_name').val(face.name);
                    $('#input_custom_code').val(face.custom_code);
                    $('#input_remark').val(face.remark || '');
                    $('#input_file').val('');
                    
                    // 显示现有图片
                    if(face.person_img_url && face.face_img_url) {
                        $('#preview_person').attr('src', face.person_img_url);
                        $('#preview_face').attr('src', face.face_img_url);
                        $('#preview_section').show();
                    } else {
                        $('#preview_section').hide();
                    }
                    
                    $('#faceModal').addClass('active');
                } else {
                    myToast2025(res.msg || '人脸不存在', 'error');
                }
            },
            error: function() {
                ele_top_loading.hide();
                myToast2025('加载失败，请稍后重试', 'error');
            }
        });
    }
    
    function closeFaceModal() {
        $('#faceModal').removeClass('active');
        currentFaceCode = '';
    }
    
    // 点击遮罩层关闭
    $('#faceModal').click(function(e) {
        if (e.target === this) {
            closeFaceModal();
        }
    });
    
    // ESC键关闭
    $(document).keydown(function(e) {
        if (e.keyCode === 27 && $('#faceModal').hasClass('active')) {
            closeFaceModal();
        }
    });
    
    function generateCode() {
        let now = new Date();
        let ymd_h = now.getFullYear().toString() + 
                    (now.getMonth() + 1).toString().padStart(2, '0') + 
                    now.getDate().toString().padStart(2, '0') + 
                    now.getHours().toString().padStart(2, '0') + 
                    now.getMinutes().toString().padStart(2, '0');
        let random = Math.floor(Math.random() * 900) + 100;
        return 'face' + ymd_h + random;
    }
    
    function submitFaceForm() {
        let group_name = $('#input_group_name').val().trim();
        let name = $('#input_name').val().trim();
        let custom_code = $('#input_custom_code').val().trim();
        let remark = $('#input_remark').val().trim();
        
        if(name === '') {
            myToast2025('请输入名称', 'error');
            return false;
        }
        if(custom_code === '') {
            myToast2025('请输入自定义编号', 'error');
            return false;
        }
        
        let handleUrl = currentHandle === 'add' ? '/face/openAdd' : '/face/openEdit';
        let formData = new FormData();
        formData.append('handle', currentHandle);
        formData.append('code', currentFaceCode);
        formData.append('group_name', group_name);
        formData.append('name', name);
        formData.append('custom_code', custom_code);
        formData.append('remark', remark);
        
        let fileInput = document.getElementById('input_file');
        if(fileInput.files.length > 0) {
            let file = fileInput.files[0];
            let fs_size = parseInt(file.size);
            let fs_size_m = parseInt(fs_size / 1024 / 1024);
            
            if(fs_size_m > 10) {
                myToast2025('文件不能超过10M: ' + fs_size_m + 'M', 'error');
                return false;
            }
            formData.append('file', file);
        } else {
            if(currentHandle === 'add') {
                myToast2025('请选择人员照片', 'error');
                return false;
            }
        }
        
        if(curIsPost) {
            myToast2025('正在提交中，请勿重复提交！', 'error', 500);
            return false;
        }
        curIsPost = true;
        
        $('#submit_loading').show();
        $('#submit_text').text('提交中...');
        
        $.ajax({
            url: handleUrl,
            type: 'post',
            async: true,
            contentType: false,
            processData: false,
            data: formData,
            dataType: 'json',
            timeout: 0,
            error: function() {
                curIsPost = false;
                $('#submit_loading').hide();
                $('#submit_text').text('提交');
                myToast2025('网络异常，请确定网络正常！', 'error');
            },
            success: function(res) {
                curIsPost = false;
                $('#submit_loading').hide();
                $('#submit_text').text('提交');
                
                if(1000 === res.code) {
                    myToast2025(res.msg, 'success', 1000);
                    setTimeout(function() {
                        closeFaceModal();
                        window.location.reload();
                    }, 1000);
                } else {
                    myToast2025(res.msg, 'error');
                }
            }
        });
    }
    
    function f_del(code){
        if(!confirm('确定要删除这个人脸数据吗？')) {
            return;
        }
        
        ele_top_loading.show();
        $.ajax({
            url: '/face/openDel',
            type: "post",
            async: true,
            data: {"code":code},
            dataType: "json",
            timeout: 0,
            error: function () {
                ele_top_loading.hide();
                myToast2025("网络异常，请确定网络正常！","error");
            },
            success: function (res) {
                ele_top_loading.hide();
                if(1000 === res.code){
                    myToast2025(res.msg, "success", 1000);
                    setTimeout(function() {
                        window.location.reload();
                    }, 1000);
                }else{
                    myToast2025(res.msg,"error");
                }
            }
        });
    }
    
    function f_showFlowCode(flow_code) {
        let html = "<option value=\"0\">请选择算法</option>";
        for (let i = 0; i < g_flowArray.length; i++) {
            let code = g_flowArray[i].code;
            let name = g_flowArray[i].name;
            if(code===flow_code){
                html += "<option selected value=\""+code+"\">"+name+"</option>";
            }else{
                html += "<option value=\""+code+"\">"+name+"</option>";
            }
        }
        eleSelectFlowCode.html(html);
    }
    
    function f_showAlgorithm(algorithmState, faceCount=0) {
        if(algorithmState){
            eleAlgorithmState.attr("class","xc_status-indicator xc_status-success");
            eleAlgorithmState.html('<i class="fa fa-circle"></i> 已开启');
            eleBtnSync.html('<i class="fa fa-refresh"></i> 全量更新人脸库('+faceCount.toString()+')');
        }else{
            eleAlgorithmState.attr("class","xc_status-indicator xc_status-error");
            eleAlgorithmState.html('<i class="fa fa-circle"></i> 未开启');
            eleBtnSync.html('<i class="fa fa-refresh"></i> 全量更新人脸库');
        }
    }
    
    function f_openAlgorithm(){
        $.ajax({
            url: '/face/openAlgorithm',
            type: "get",
            async: true,
            timeout: 0,
            error: function () {
                f_showAlgorithm(false);
            },
            success: function (res) {
                if(1000 === res.code){
                    let info = res.info;
                    let state = info["state"];
                    if(state){
                        let flowCode = info["flowCode"];
                        let faceCount = info["faceCount"];
                        f_showFlowCode(flowCode);
                        f_showAlgorithm(true,faceCount);
                    }else{
                        f_showAlgorithm(false);
                    }
                }else{
                    f_showAlgorithm(false);
                    console.log(res.msg)
                }
            }
        });
    }
    
    function f_openAlgorithmInit(){
        let flow_code = eleSelectFlowCode.val().trim();
        
        if(flow_code === "0"){
            myToast2025("请选择算法","error");
            return;
        }
        
        ele_top_loading.show();
        $.ajax({
            url: '/face/openAlgorithmInit',
            type: "post",
            async: true,
            data: {"flow_code":flow_code},
            dataType: "json",
            timeout: 0,
            error: function () {
                ele_top_loading.hide();
                f_showAlgorithm(false);
                myToast2025("网络异常，请确定网络正常！","error");
            },
            success: function (res) {
                ele_top_loading.hide();
                if(1000 === res.code){
                    f_showAlgorithm(true);
                    myToast2025("人脸算法已开启", "success");
                }else{
                    f_showAlgorithm(false);
                    myToast2025(res.msg,"error");
                }
            }
        });
    }
    
    function f_openAlgorithmRelease(){
        if(!confirm('确定要关闭人脸算法吗？')) {
            return;
        }
        
        ele_top_loading.show();
        $.ajax({
            url: '/face/openAlgorithmRelease',
            type: "post",
            async: true,
            data: {},
            dataType: "json",
            timeout: 0,
            error: function () {
                ele_top_loading.hide();
                f_showAlgorithm(false);
                myToast2025("网络异常，请确定网络正常！","error");
            },
            success: function (res) {
                ele_top_loading.hide();
                f_showAlgorithm(false);
                if(1000 === res.code){
                    myToast2025("人脸算法已关闭", "success");
                }else{
                    myToast2025(res.msg,"error");
                }
            }
        });
    }
    
    function f_openSyncDatabase(group_name) {
        ele_top_loading.show();
        $.ajax({
            url: '/face/openSyncDatabase',
            type: "post",
            async: true,
            data: {"group_name":group_name},
            dataType: "json",
            timeout: 0,
            error: function () {
                ele_top_loading.hide();
                myToast2025("网络异常，请确定网络正常！","error");
            },
            success: function (res) {
                ele_top_loading.hide();
                if(1000 === res.code){
                    let faceCount = res.info["faceCount"];
                    f_showAlgorithm(true,faceCount);
                    myToast2025(res.msg,"success",1000);
                }else{
                    myToast2025(res.msg,"error");
                }
            }
        });
    }
    
    function viewImage(url) {
        $.fancybox.open({
            src: url,
            type: 'image'
        });
    }

    $(document).ready(function () {
        f_openAlgorithm();
    });
</script>
{% endblock javascripts %}
